#ifndef CMATH_H
#define CMATH_H

#define NULL 0
#include "datastructures.h"
//дробный модуль
//=========================================================================
double dabs( double val);

//векторное произведение
//=========================================================================
double vec_mult( Point &a, Point &b, Point &c);

//скалярное произведение
//=========================================================================
double scal_mult( Point &a, Point &b, Point &c );

//функция определяет принадлежность точки point треугольнику t1_t2_t3
//=========================================================================
bool isInTriangle( Point &point,  Point &t1, Point &t2, Point &t3 );

//=========================================================================
bool isInTriangle(Point &p, Triangle &t);

//=========================================================================
double distance(Point &p1, Point &p2);


//функция определяет направление обхода многоугольника
//=========================================================================
bool clwDirection(const std::vector <Point> points);


template <typename T>
struct Node
{
    int key;
    T p;
    Node *next;
};

template <typename T>
struct SList
{
    SList() { size = 0; head = tail = NULL; }
    SList( SList &s ){ size = s.size; head = s.head; tail = s.tail; }
    void appendtoTail(T &t);
    void delete_(int _key);
    void print_list();
    Node <T>* find(int );
    void clear();

    int size;
    Node<T> *head, *tail;
};
//добавление элемента T в список
template <typename T>
void SList <T> ::appendtoTail(T &t)
{
    Node <T> *node = new Node <T> ();
    if(!node) return;
    node->key = size;
    node->p = t;
    if(size == 0)
    {
        node->next = node;
        head = tail = node;
        size = 1;
        return;
    }
    tail->next = node;
    tail = node;
    node->next = head;
    size++;
}
//поиск
template <typename T>
Node <T> * SList<T>::find(int key)
{
    Node <T> *n = head;

    while( n->next != head )
    {
        if( n->next->key == key )	return n;
        n = n->next;
    }
    if( n->next->key == key )	return n;
    return NULL;
}
//удаление
template <typename T>
void SList<T>::delete_(int _key)
{
    Node<T> *n = find(_key), *t;

    if( n == NULL || n->next->key != _key )	return;

    if( head == n->next )
        head = n->next->next;

    if( tail == n->next )
    {
        tail = n;
        head = tail->next->next;
    }
    size--;

    t = n->next->next;
    delete(n->next);
    n->next = t;
}
//очистка списка
template <typename T>
void SList<T>::clear()
{
    Node <T> *pn = head, *pr;
/**/
    while( pn != tail )
    {
        pr = pn;
        pn = pn->next;
        delete(pr);
        pr = NULL;
    }
    delete(pn);
    pn = NULL;
/**/
    head = tail = NULL;
    size = 0;
}

#endif // CMATH_H
